const express = require('express')
const router = express.Router()
const moment = require('moment')
const AccountModel = require('../../models/AccountModel')
const checkTokenMiddleWare = require('../../middlewares/checkTokenMiddleware')

router.get('/account', checkTokenMiddleWare, (req, res, next) => {
  console.log(req.user)
  AccountModel.find()
    .sort({ time: -1 })
    .exec((err, data) => {
      if (err) {
        res.json({
          code: '1001',
          msg: '读取失败',
          data: null
        })
        return
      }
      res.json({
        code: '0000',
        msg: '读取成功',
        data
      })
    })
})

router.post('/account', checkTokenMiddleWare, (req, res, next) => {
  // 表单验证
  const ruleForm = {
    title: '标题',
    time: '时间',
    account: '金额',
    remarks: '备注'
  }
  for (const key in ruleForm) {
    if (!req.body[key]) {
      return res.json({
        code: '1001',
        msg: `${ruleForm[key]}为必填`,
        data: null
      })
    }
  }

  AccountModel.create(
    {
      ...req.body,
      time: moment(req.body.time).toDate()
    },
    (err, data) => {
      if (err) {
        return res.json({
          code: '1001',
          msg: '插入失败',
          data: null
        })
      }
      res.json({
        code: '0000',
        msg: '保存成功',
        data
      })
    }
  )
})

router.delete('/account/:id', checkTokenMiddleWare, (req, res) => {
  // 获取 params 的 id 参数
  let id = req.params.id
  // 删除
  // db.get('accounts').remove({ id }).write()
  AccountModel.deleteOne({ _id: id }, (err, data) => {
    if (err) {
      // res.status(500).send('删除失败')
      res.json({
        code: '1001',
        msg: '删除失败',
        data: null
      })
      return
    }
    // res.render('success', { msg: '账单删除成功', url: '/account' })
    res.json({
      code: '0000',
      msg: '删除成功',
      data: null
    })
  })
})

// 获取单个账单信息
router.get('/account/:id', checkTokenMiddleWare, (req, res) => {
  // 获取 id 参数
  let { id } = req.params
  AccountModel.findById(id, (err, data) => {
    if (err) {
      return res.json({
        code: '1001',
        msg: '读取失败',
        data: null
      })
    }
    res.json({
      code: '0000',
      msg: '读取成功',
      data
    })
  })
})

// patch
router.patch('/account/:id', checkTokenMiddleWare, (req, res, next) => {
  let { id } = req.params

  AccountModel.updateOne(
    {
      _id: id
    },
    req.body,
    (err, data) => {
      if (err) {
        return res.json({
          code: '1001',
          msg: '更新失败',
          data: null
        })
      }
      AccountModel.findById(id, (err, data) => {
        if (err) {
          return res.json({
            code: '1001',
            msg: '读取失败',
            data: null
          })
        }
        res.json({
          code: '0000',
          msg: '更新成功',
          data
        })
      })
    }
  )
})

module.exports = router
